const App = {
  mixins: [Save],
  data() {
    return {
      selectedOrganizations: [], // 存储所有党组织（含选中状态）
      originalSelectedOrgs: [], // 初始加载的组织（含主键）
      filterText: "",
      treeData: [],
      dialogFormVisible: false,
      Organization_SerialNumber: "",
      loading: false // 新增加载状态
    };
  },
  computed: {
    selectedCount() {
      return this.selectedOrganizations.filter(org => org.checked).length;
    },
    // 计算当前显示的被选中组织（用于表格展示）
    selectedOrganizationsDisplay() {
      let _this = this;
      let tabReturn = _this.selectedOrganizations.filter(org => org.checked)
      if (tabReturn.length > 0) {
        return tabReturn;
      }
      else { return []; }
    }
  },
  mounted() {
    let ls_URL = window.location.href;
    this.Organization_SerialNumber = getQueryObject(ls_URL, "Organization_SerialNumber");
    this.Setparty_organizationTree();
    this.Getplan_memberAndSetData(this.Organization_SerialNumber);
  },
  watch: {
    filterText(newVal) {
      if (this.$refs.tree) {
        this.$refs.tree.filter(newVal);
      }
    },
  },
  methods: {
    // 过滤树节点
    filterNode(value, data) {
      if (!value) return true;
      return data.Party_Organization_Name.includes(value);
    },

    // 处理节点点击（新增记录）
    handleNodeClick(data) {
      const exists = this.selectedOrganizations.some(
        org => org.Party_Organization_SerialNumber === data.Party_Organization_SerialNumber
      );

      if (!exists) {
        this.selectedOrganizations.push({
          ...data,
          checked: true,
          isNew: true // 标记为新增记录
        });
      }
    },

    // 清空所有选择
    clearAll() {
      this.selectedOrganizations = [];
    },

    // 处理复选框变化
    handleCheckboxChange(option) {
      // 标记删除状态（如果是原始记录且被取消选中）
      if (!option.isNew && !option.checked) {
        option.isDeleted = true;
      }
    },

    // 获取党组织树
    Setparty_organizationTree() {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
        type: "GET",
        data: {
          TableName: "party_organization",
          NodeCode: "",
        },
        success: (data) => {
          _this.treeData = data.map(item => ({
            ...item,
            children: item.children || []
          }));
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },

    // 打开对话框
    xin() {
      this.dialogFormVisible = true;
    },

    // 提交方法
    handleSubmit2() {
      this.loading = true;

      // 1. 准备删除记录 - 原始存在但当前未选中
      const deleteRecords = this.originalSelectedOrgs
        .filter(org =>
          !this.selectedOrganizations.some(
            s => s.Party_Organization_SerialNumber === org.Party_Organization_SerialNumber && s.checked
          )
        )
        .map(org => ({
          ...org,
          Row_Status: "1", // 标记删除
          //Party_Organization_SerialNumber: org.Party_Organization_SerialNumber // 添加关键字段
        }));

      // 2. 准备新增记录 - 当前选中且是新增
      const addRecords = this.selectedOrganizations
        .filter(org => org.checked && org.isNew)
        .map(org => ({
          Organization_SerialNumber: this.Organization_SerialNumber,
          // ChildrenOrg_SerialNumber: org.Party_Organization_SerialNumber,
          Party_Organization_SerialNumber: org.Party_Organization_SerialNumber
        }));

      // 3. 构建数据集
      const lJSONObject_DataSet = {};

      // 确保删除记录包含主键字段
      if (deleteRecords.length > 0) {
        lJSONObject_DataSet.Modify = {
          'north_organization_childrenorg': deleteRecords
        };
      }

      if (addRecords.length > 0) {
        lJSONObject_DataSet.Add = {
          'north_organization_childrenorg': addRecords
        };
      }
      console.log(lJSONObject_DataSet);

      // 4. 提交数据
      if (Object.keys(lJSONObject_DataSet).length > 0) {
        submitSave(lJSONObject_DataSet, (res) => {
          this.loading = false;
          if (res.Status == 'success') {
            this.$message.success('操作成功');
            setTimeout(() => {
              window.location.href = './index.html';
            }, 1500);
          } else {
            this.$message.error('操作失败: ' + res.Message);
          }
        });
      } else {
        this.loading = false;
        this.$message.info('没有需要保存的变更');
      }
    },

    // 返回上一页
    goBack() {
      window.history.back();
    },

    // 修改后的初始化方法（确保获取主键）
    Getplan_memberAndSetData(arg) {
      const _this = this;


      $.ajax({
        headers: requestHeaders(),

        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "POST",
        data: {
          Data: 'north_organization_childrenorg', //sql名
          Condition: " Row_Status='0' and  Organization_SerialNumber='" + arg + "'"
        },
        success: (res) => {

          if (res.length > 0) {
            this.originalSelectedOrgs=res;

            //把 name 和 创建日期 查询出来
            $.ajax({
              headers: requestHeaders(),
              url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
              method: "post",
              data: {
                SQLSerialNumber: "SQL_north_organization_childrenorg",
                Condition: "",
                ExtensionCondition: window.btoa(
                  unescape(
                    encodeURIComponent(
                      " where north_organization_childrenorg.Row_Status='0' and  north_organization_childrenorg.Organization_SerialNumber='" + arg + "'"
                    )
                  )
                ),
              },
              success: (resContain) => {
                // 初始化选中状态（添加主键和状态标记）
                _this.selectedOrganizations = res.map(item => {
                  let filter1=resContain.filter(fi=>fi.ChildrenOrg_SerialNumber===item.ChildrenOrg_SerialNumber);

                  return {
                  ...item,
                  Party_Organization_Name: filter1[0].Party_Organization_Name,
                  Establishment_Date: filter1[0].Establishment_Date,
                  checked: true,
                  isNew: false, // 标记是否为新增
                  isDeleted: false // 初始化删除标记
                }
              });
              console.log("带原值的",_this.selectedOrganizations);
              
              },
              complete: (XMLHttpRequest) => {
                requestPretreatment(XMLHttpRequest);
              },
            });
          }
          else {


          }
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });


    },
  }
};

const { createApp } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
app.mount("#app");